<template>
  <el-dialog class="second-dialog" v-model="showSecondDialog" width="400" draggable :modal="false">
    <template #header>
      <div class="my-second-header">
        <h2>{{ operationType ? '修改用户信息' : '新增交通部门用户' }}</h2>
      </div>
    </template>
    <el-form label-width="auto" :model="formData" :rules="formRules" status-icon ref="formEl">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model.trim="formData.userName" placeholder="请输入用户名" clearable></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="loginPwd">
        <el-input
          v-model.trim="formData.loginPwd"
          type="password"
          placeholder="请输入密码"
          clearable
          show-password
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer-btns">
        <el-button type="primary" @click="handleConfirm">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { useTemplateRef, watch } from 'vue'
import { addUser, modifyUser } from '@/api/admin'
import { ElMessage } from 'element-plus'

const formEl = useTemplateRef('formEl')

const showSecondDialog = defineModel('showSecondDialog')
const formData = defineModel('formData')

const { selectedId, operationType, formRules } = defineProps({
  selectedId: {
    type: Number,
    required: true,
  },
  operationType: {
    type: Number,
    required: true,
  },
  formRules: {
    type: Object,
    default: () => ({}),
  },
})

const emit = defineEmits(['operationSuccess'])

const handleConfirm = async () => {
  if (!formEl.value) return
  await formEl.value.validate(async (valid) => {
    if (!valid) return
    try {
      if (operationType) {
        await modifyUser({ id: selectedId, ...formData.value })
      } else {
        await addUser(formData.value)
      }
      ElMessage({
        message: `操作成功`,
        type: 'success',
      })
      if (formEl.value) formEl.value.resetFields()
      emit('operationSuccess', true)
      showSecondDialog.value = false
    } catch {
      ElMessage({
        message: `操作失败`,
        type: 'error',
      })
    }
  })
}
const handleCancel = () => {
  if (formEl.value) {
    formEl.value.resetFields()
  }
  emit('operationSuccess', false)
  showSecondDialog.value = false
}

watch(showSecondDialog, (val) => {
  if (!val) {
    if (formEl.value) {
      formEl.value.resetFields() //将表单重置为初始值并移除校验结果,但初始值可能不是空的
      formData.value = {} //清空表单数据
    }
  }
})
</script>

<style lang="scss" scoped>
.second-dialog {
  .my-second-header {
    font-size: 1.2rem;
    color: #666;
    font-weight: 600;
  }
  :deep(.el-dialog__body) {
    padding-bottom: 18px;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
    .el-form {
      margin-top: 18px;
      .el-form-item {
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
}
</style>
